import { constantRoutes } from '@/router'
import { getMenus } from '@/api/user'
import { getAsyncRoutes } from '@/router/modules/table'
import router from '@/router'
let userPermissions = ['admin'] // 假设用户拥有admin权限
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.permissions) {
    return roles.some(role => route.meta.permissions.includes(role))
  } else if (route.children && route.children.length) {
    return route.children.some(val => val.meta.permissions.some(key => roles.includes(key)))
  } else {
    return true
  }
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}
const state = {
  routes: [],
  btns: []
}
const mutations = {
  SET_ROUTES: (state, routes) => {
    // state.routes = constantRoutes.concat(routes)
    state.routes = filterAsyncRoutes(constantRoutes, userPermissions)
  },
  SET_BTNS: (state, list) => {
    state.btns = list
  },
  RESET_ROUTES: (state) => {
    state.routes = []
  }
}
// 重组btn数据
function rebuild(data, list) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].children.length > 0) {
      rebuild(data[i].children, list)
    }
    if (data[i].menu_status === '0') {
      list.push(data[i].href)
    }
  }
  return list
}
const actions = {
  getRoutes({ commit }, roles) {
    console.log(roles)
    return new Promise(resolve => {
      // getMenus({}).then(res => {
      // 	console.log('-----------', res.data.menuInfo)
      // 	const arr = res ? res.data.menuInfo : []
      // 	const menuList = getAsyncRoutes(arr)
      // 	router.addRoutes(menuList)
      // 	let list = [];
      // 	console.log('角色权限', rebuild(arr, list))
      // 	commit('SET_BTNS', rebuild(arr, list))
      // 	commit('SET_ROUTES', menuList)
      // 	resolve(menuList)
      // })
      userPermissions = roles
      commit('SET_ROUTES', [])
      resolve([])
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
